import { getToken, removeToken, setToken } from '@/utils/auth'
import { getUserInfoAPI, loginAPI } from '@/api'
// import { getUserInfoAPI, loginAPI } from '@/api'
const state = {
  token: getToken(), // 初始化的时候从本地缓存读取
  userInfo: {} // 存储用户信息
}
const mutations = {
  setToken(state, token) {
    state.token = token
    // 同步到持久化
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken() // 删除本地缓存的token
  },
  setUserInfo(state, preload) {
    state.userInfo = preload // 更新mutations
  }
}
// 发送axios
const actions = {
  // 登录请求
  async login(store, data) {
    store.commit('setToken', await loginAPI(data))
  },
  // 获取用户信息
  async getUserInfo(store) {
    store.commit('setUserInfo', await getUserInfoAPI()) // 设置用户信息
  },
  // 登出
  logout(store) {
    store.commit('removeToken') // 删除token
    store.commit('setUserInfo', {}) // 删除用户信息
  }

}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
